import router from './router'
import store from './store'
import { getSid } from '@/utils/auth'
import jwt from 'jsonwebtoken'
import moment from 'moment'

router.beforeEach(async (to, from, next) => {
  const hasSid = getSid()

  if (hasSid) {
    const token = store.state.token
    const payload = jwt.decode(token)
    if (token !== '' && token !== null) {
      if (moment().isBefore(moment(payload.exp * 1000))) {
        next()
      } else {
        store.commit('logout')
        if (to.meta.requiresAuth) {
          next('/login')
        } else {
          next()
        }
      }
    } else {
      next()
    }
  } else {
    store.commit('setSid')
    next()
  }
})
